package com.web.nyist.interceptor;

import com.sun.xml.internal.ws.util.ByteArrayDataSource;
import com.web.nyist.service.HtmlService;
import com.web.nyist.util.RequestUtil;
import com.web.nyist.util.ThreadLocalUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 所有功能的共用拦截器，主要是向modelandview中加入一些常用的基路径
 * Created by penghuiping on 3/17/15.
 */
@Component
public class CommonInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = Logger.getLogger(CommonInterceptor.class);

    @Resource
    HtmlService htmlService;

    @Value("${base_assets_url}")
    private String base_assets_url;

    @Value("${base_assets_upload_url}")
    private String base_assets_upload_url;

    @Resource(name = "mailSender")
    private JavaMailSender mailSender;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("开始访问" + request.getRequestURL().toString());
        ThreadLocalUtil.set(request);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        String ip= RequestUtil.getIpAddr(request);
        String hostName= RequestUtil.getHostName(ip);
        String macAddress= RequestUtil.getMacAddress(ip);
        String requestBrowserInfo= RequestUtil.getRequestBrowserInfo(request);
        String requestSystemInfo= RequestUtil.getRequestSystemInfo(request);
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
        String content="\nip:"+ip+"\n"+
                "hostName:"+hostName+"\n"+
                "macAddress:"+macAddress+"\n"+
                "requestBrowserInfo:"+requestBrowserInfo+"\n"+
                "tempContextUrl:"+tempContextUrl+"\n"+
                "requestSystemInfo:"+requestSystemInfo+"\n";
        logger.info("访问信息：" + content);
        sendMail("开始加载视图","cao.yonghao@puscene.com","访问信息：\n"+request.getRequestURL().toString()+content);

        if (null != modelAndView) {

            modelAndView.getModelMap().addAttribute("ctx", htmlService.getBasePath(request));
            modelAndView.getModelMap().addAttribute("frontAssetsUrl", htmlService.getBasePath(request) + "/assets/front/");
            modelAndView.getModelMap().addAttribute("adminAssetsUrl", htmlService.getBasePath(request) + "/assets/admin/");
            modelAndView.getModelMap().addAttribute("apiAssetsUrl", htmlService.getBasePath(request) + "/assets/api/");
            modelAndView.getModelMap().addAttribute("uploadAssetsUrl", htmlService.getBasePath(request));
        }
        logger.info("开始加载视图" + request.getRequestURL().toString());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("结束加载视图" + request.getRequestURL().toString());
    }


    /**
     * 方法名: sendMail
     * 描述: 发送邮件
     * 参数: @param subject
     * 参数: @param toMail
     * 参数: @param content
     * 参数: @param files
     * 参数: @return
     * 返回类型: boolean
     */
    public boolean sendMail(String subject, String toMail, String content) {
        boolean isFlag = false;
        Map<String, Object> logMap=new HashMap<String, Object>();
        try {
            MimeMessage message = mailSender.createMimeMessage();
            logMap.put("sendMailLog", "sendMailLog");
            String emails[] = toMail.split(",");

            logMap.put("emails", emails);

            for (int i = 0; i < emails.length; i++) {
                String email = emails[i];
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                logMap.put("sendInfoTo" + i, "发送给" + email + "mailInfo:" + "subject:" + subject + ";content:" + content + ";");
                helper.setFrom(new InternetAddress(((JavaMailSenderImpl) mailSender).getUsername(), "访问通知：" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + ""));
                helper.setSubject(subject);
                helper.setTo(email);
                helper.setText(content);
                isFlag = true;
                mailSender.send(message);
            }
        } catch (Exception e) {
            isFlag = false;
        }
        logger.info("mail:" + logMap);
        return isFlag;
    }
}
